<template>
  <el-dialog
    v-model="open"
    :title="title"
    width="400px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="dialogClosed"
  >
    <el-upload
      v-model:file-list="fileList"
      ref="uploadRef"
      accept=".xlsx, .xls"
      action=""
      :limit="1"
      :auto-upload="false"
      drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <template #tip>
        <div class="flex flex-col items-center mt-2 text-xs">
          <div>
            <span>仅允许导入xls、xlsx格式文件。 </span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="handleDownloadTpl"
            >
              下载模板
            </el-link>
          </div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="isUploading" @click="submitFileForm">确定</el-button>
        <el-button @click="open = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref } from 'vue';
  import modal from '@/plugins/modal';

  const props = defineProps({
    importData: {
      type: Function,
      default: () => {},
    },
    handleDownloadTpl: {
      type: Function,
      default: () => {},
    },
    fileSize: {
      type: Number,
      default: 50,
    },
    fileType: {
      type: Array,
      default: () => ['xlsx', 'xls'],
    },
  });
  const emit = defineEmits(['success']);

  const fileList = ref([]);
  const isUploading = ref(false);
  const title = ref('');
  const open = ref(false);
  const uploadRef = ref(null);

  function handleImport() {
    title.value = '导入';
    open.value = true;
  }

  function submitFileForm() {
    const file = handleBeforeUpload();
    if (file) {
      isUploading.value = true;
      const formData = new FormData();
      formData.append('file', file.raw);
      props
        .importData(formData)
        .then(({ msg }) => {
          modal.msg(msg);
          open.value = false;
          uploadRef.value?.clearFiles();
          emit('success');
        })
        .finally(() => {
          isUploading.value = false;
        });
    }
  }

  function handleBeforeUpload() {
    // 检查数量
    if (fileList.value.length === 0) {
      modal.msgError('请添加文件!');
      return false;
    }

    const file = fileList.value[0];

    // 校检文件类型
    if (props.fileType.length) {
      const fileName = file.name.split('.');
      const fileExt = fileName[fileName.length - 1];
      const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
      if (!isTypeOk) {
        modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
        return false;
      }
    }

    // 校检文件大小
    if (props.fileSize) {
      const isLt = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt) {
        modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
        return false;
      }
    }

    return file;
  }

  function dialogClosed() {
    fileList.value = [];
    isUploading.value = false;
    title.value = '';
  }

  defineExpose({
    handleImport,
  });
</script>
